import { postAxiosRequest } from '@/services/common';

// 权限常量
const lookCode = 0b1;
const editCode = 0b10;

// 获取表单详情
export const getFormDetail = (uuid, initChecked = false, formItemConfigs = null) => {
  return new Promise((resolve, reject) => {
    postAxiosRequest("/form/formBasicConfigure/getDetailByUuid", {
      uuid: uuid,
    })
      .then((res) => {
        if (res?.formDesign?.designJson) {
          let formItems = [];
          try {
            const designJson = JSON.parse(res?.formDesign?.designJson);
            if (Array.isArray(designJson.list)) {
              formItems = designJson.list;
            }
            const tableConfig = handleFormItem(formItems, formItemConfigs, initChecked);
            formItems = tableConfig.formItems;
            resolve({
              formItems,
              formDesign: res,
              checkedLook: tableConfig.checkedLook || [],
              checkedEdit: tableConfig.checkedEdit || [],
            });
          } catch (error) {
            reject(error);
          }
        } else {
          reject(new Error("表单设计数据为空"));
        }
      })
      .catch((error) => {
        reject(error);
      });
  })
}

// 获取表单配置
export const getTableConfig = (table) => {
  return new Promise((resolve, reject) => {
    // 返回一个对象 对象key为model value为edit look  当配置勾选了 对应生成edit以及look
    if (Array.isArray(table)) {
      const config = {};
      table.forEach((item) => {
        const look = item.look ? lookCode : 0;
        const edit = item.edit ? editCode : 0;
        config[item.model] = look + edit;
      });
      resolve(config);
    } else {
      reject(new Error("table配置错误"));
    }
  })
}

// 加载并获取
export const loadAndGetFormDetail = (uuid, initChecked) => {
  return new Promise(async (resolve, reject) => {
    try {
      const { formItems, formDesign } = await getFormDetail(uuid, initChecked);
      const tableConfig = await getTableConfig(formItems);
      resolve({ formItems, formDesign, tableConfig });
    } catch (error) {
      reject(error);
    }

  })
}

// 处理表单元素
function handleFormItem(formItems, formItemConfigs, initChecked) {
  const tableConfig = {
    formItems: [],
    checkedLook: [],
    checkedEdit: [],
  };
  if (!formItemConfigs) {
    tableConfig.formItems = formItems.map((item, index) => {
      if(initChecked) {
        tableConfig.checkedLook.push(index);
        tableConfig.checkedEdit.push(index);
      }
      return {
        name: `${item.label}(${item.model})`,
        model: item.model,
        look: initChecked,
        edit: initChecked,
      };
    });
  }else{
    tableConfig.formItems = formItems.map((item, index) => {
      return vailAuth(item, formItemConfigs, index, tableConfig.checkedLook, tableConfig.checkedEdit);
    })
  }
  return tableConfig;
}

// 验证表单元素是否有对应权限
function vailAuth(item, formItemConfigs, index, checkedLook, checkedEdit) {
  const { model } = item;
  const authCode = formItemConfigs[model];
  const configs = {
    look: false,
    edit: false,
    name: `${item.label}(${item.model})`,
    model: item.model,
  }
  // 确定权限码是否是包含对应权限
  if (valiCode(authCode, 'look')) {
    configs.look = true;
    checkedLook && checkedLook.push(index);
  }
  if (valiCode(authCode, 'edit')) {
    configs.edit = true;
    checkedEdit && checkedEdit.push(index);
  }
  return configs;
}

// 验证权限码是否包含对应权限
function valiCode(authCode, type = "edit") {
  return authCode & (type === "edit" ? editCode : lookCode);
}

// 解析表单元素权限
export function parseItemAuth(element, authCode) {
  const options = element.options || {};
  options.hidden = !valiCode(authCode, 'look');
  options.disabled = !valiCode(authCode, 'edit');
}